package com.zhugang.week05;

/**
 * @program algorithms
 * @description: BSearchFirst
 * @author: chanzhugang
 * @create: 2022/07/04 15:39
 */
public class BSearchFirstEquals {


    public static void main(String[] args) {
        BSearchFirstEquals bSearchFirstEquals = new BSearchFirstEquals();
        int[] a = new int[]{2, 3, 4, 4, 4, 7, 9};
        int index = bSearchFirstEquals.bSearchFirst(a, a.length, 4);
        System.out.println(index);

    }

    /**
     * 查找第一个值等于给定值的元素（下标）
     *
     * @param a
     * @param n
     * @param target
     * @return
     */
    public int bSearchFirst(int[] a, int n, int target) {
        // 先把标准二分写出来
        int low = 0;
        int high = n - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            // int mid = (low + high) / 2;
            if (a[mid] == target) {
                if (mid == 0 || a[mid - 1] != target) {
                    // 真命中（第一个）：向前探测法
                    return mid;
                } else {
                    // 伪命中
                    high = mid - 1;
                }
            } else if (a[mid] > target) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }
}